from PyQt5.QtWidgets import (QWidget, QLabel, QVBoxLayout, QHBoxLayout,
                             QPushButton, QRadioButton, QButtonGroup, QFrame,
                             QScrollArea, QTextEdit, QSizePolicy, QCheckBox)  # 添加 QCheckBox
from PyQt5.QtCore import Qt
import sys
from io import StringIO
from Data.Chinese import model_number
from Data.English import model_number_en


class OutputInterceptor(StringIO):
    def __init__(self, label):
        super().__init__()
        self.label = label
        self.original_stdout = sys.stdout
        self.all_text = []

    def write(self, text):
        super().write(text)
        if not text.strip():
            return
            
        # 处理ANSI颜色转义序列
        text = text.replace('\033[95m', '<span style="color: #9370DB;">')  # 紫色
        text = text.replace('\033[33m', '<span style="color: #FFA500;">')  # 橙色
        text = text.replace('\033[93m', '<span style="color: #FFA500;">')  # 橙色（兼容）
        text = text.replace('\033[91m', '<span style="color: #FF0000;">')  # 红色
        text = text.replace('\033[0m', '</span>')
        
        # 直接添加新文本并更新显示
        self.all_text.append(text.strip())
        self.update_display()
        # 强制处理事件，实现实时显示
        from PyQt5.QtCore import QCoreApplication
        QCoreApplication.processEvents()

    def update_display(self):
        if self.all_text:
            html = """
            <div style='font-family: "Microsoft YaHei"; line-height: 1.5; margin: 0; padding: 0;'>
                {}
            </div>
            """.format('<br>'.join(self.all_text))
            self.label.setHtml(html)
            # 滚动到底部
            self.label.verticalScrollBar().setValue(
                self.label.verticalScrollBar().maximum()
            )

class CommandUI(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()

    def run_process(self):
        # 清空之前的信息
        self.info_label.clear()

        # 设置输出重定向
        output_interceptor = OutputInterceptor(self.info_label)
        sys.stdout = output_interceptor

        try:
            from Data.command_table import table
            is_folder = self.folder_radio.isChecked()
            export_excel = self.export_excel.isChecked()
            table(is_folder, export_excel)
        finally:
            # 恢复标准输出
            sys.stdout = output_interceptor.original_stdout

    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(50, 30, 50, 30)

        # 创建标题
        title = QLabel('11x命令表格检查')
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet('font-size: 30px; color: #2c3e50; margin: 5px 0 15px 0;')

        # 第二组单选按钮（文件选择）
        file_container = QWidget()
        file_layout = QHBoxLayout(file_container)
        file_layout.setAlignment(Qt.AlignCenter)
        self.file_button_group = QButtonGroup()

        self.folder_radio = QRadioButton("选择文件夹")
        self.file_radio = QRadioButton("选择文件")
        self.export_excel = QCheckBox("导出Excel")  # 改为复选框
        self.folder_radio.setChecked(True)  # 默认选择文件夹
        self.export_excel.setChecked(True)  # 默认勾选导出Excel
    
        # 设置单选按钮和复选框样式
        radio_style = """
            QRadioButton, QCheckBox {
                font-size: 16px;
                color: #696969;
                padding: 3px;
                spacing: 8px;
                margin-top: 5px;
            }
            QRadioButton::indicator, QCheckBox::indicator {
                width: 15px;
                height: 15px;
            }
        """
    
        # 设置按钮样式
        for widget in [self.folder_radio, self.file_radio, self.export_excel]:
            widget.setStyleSheet(radio_style)
    
        self.file_button_group.addButton(self.folder_radio)
        self.file_button_group.addButton(self.file_radio)
        # 移除 self.export_excel 从按钮组中的添加，因为它现在是复选框
    
        file_layout.addWidget(self.folder_radio)
        file_layout.addSpacing(30)
        file_layout.addWidget(self.file_radio)
        file_layout.addSpacing(30)
        file_layout.addWidget(self.export_excel)
    
        # 创建运行按钮
        run_button = QPushButton('运行')
        run_button.setFixedSize(200, 40)
        run_button.setStyleSheet("""
            QPushButton {
                background-color: #1E90FF;
                color: white;
                border: none;
                border-radius: 6px;
                font-size: 16px;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
            QPushButton:pressed {
                background-color: #a93226;
            }
        """)
        run_button.clicked.connect(self.run_process)
    
        # 创建分割线
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setStyleSheet("background-color: #A9A9A9;")
        line.setFixedHeight(2)
    
        # 创建信息显示区域
        self.info_label = QTextEdit()
        self.info_label.setReadOnly(True)
        self.info_label.setStyleSheet("""
            QTextEdit {
                color: #228B22;
                font-size: 14px;
                font-family: "Microsoft YaHei";
                margin-top: 10px;
                background-color: #F0FFF0;
                border: none;
                line-height: 1.2;
            }
            QTextEdit p {
                margin: 0;
                padding: 0;
                line-height: 1.2;
            }
        """)
        self.info_label.setAcceptRichText(True)  # 允许富文本显示
    
        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidget(self.info_label)
        scroll_area.setWidgetResizable(True)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background-color: #F0FFF0;
            }
            QScrollBar:vertical {
                width: 10px;
                background: #F0FFF0;
            }
            QScrollBar::handle:vertical {
                background: #A9A9A9;
                border-radius: 5px;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                height: 0px;
            }
        """)
        scroll_area.setMinimumHeight(300)
        scroll_area.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
    
        # 添加所有组件到主布局
        layout.addWidget(title)
        layout.addSpacing(5)
        layout.addWidget(file_container)
        layout.addSpacing(15)
        layout.addWidget(run_button, alignment=Qt.AlignCenter)
        layout.addSpacing(10)
        layout.addWidget(line)
        layout.addWidget(scroll_area, 1)
